package com.zqh.forum.services.impl;

import com.zqh.forum.common.AppResult;
import com.zqh.forum.common.ResultCode;
import com.zqh.forum.dao.ArticleReplyMapper;
import com.zqh.forum.exception.ApplicationException;
import com.zqh.forum.model.ArticleReply;
import com.zqh.forum.services.IArticleReplyService;
import com.zqh.forum.services.IArticleService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 帖子接口定义类
 */
@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Autowired
    private ArticleReplyMapper articleReplyMapper;

    @Autowired
    private IArticleService articleService;

    @Override
    public void create(ArticleReply articleReply) {
        //非空校验
        if(articleReply == null ||
                articleReply.getArticleId() == null ||
                articleReply.getPostUserId() == null ||
                !StringUtils.hasLength(articleReply.getContent())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date = new Date();
        articleReply.setUpdateTime(date);
        articleReply.setCreateTime(date);

        //写入数据库
        int row = articleReplyMapper.insertSelective(articleReply);
        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新帖子表的回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());
        //打印日志
        log.info("回复成功，article id = " + articleReply.getArticleId() + "user id = " + articleReply.getPostUserId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        //非空校验
        if(articleId == null || articleId<=0 ){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO
        List<ArticleReply> articleReplies = articleReplyMapper.selectByArticleId(articleId);
        //返回结果
        return articleReplies;
    }
}
